/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package control;

import fsm.Board;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import util.Constants;
import util.LOG;
import util.Timer;

/**
 *
 * @author mike.boddin
 */
public class SolveAlgorithmBruteForce {
    /**
     * Key-Value-Pairs:
     * Key              <--> Value :Type
     * Constants.BOARD  <--> board :Board
     * Constants.POINTS <--> points :Integer
     * Constants.CLICKS <--> indexes of fields, wich were clicked :List<Integer>
     */
    public Solution solve(Board board){
        return getMaxPoints(board, new ArrayList<Integer>(), 0);
    }

    private Solution getMaxPoints(Board board, ArrayList<Integer> clicks, int points){
        ArrayList<HashSet<Integer>> allGroups = board.getAllGroups(true);
        LOG.debug("[getMaxPoints] we have following groups: ");
        for(int i=0;i<allGroups.size();i++){
            LOG.debug(Arrays.toString(allGroups.get(i).toArray()));
        }

        //abbruchbedingung
        if(allGroups.isEmpty() || Timer.getTimeInSeconds()==Constants.MAXTIME){
            LOG.info("[getMaxPoints] stop recursion; no more groups: "+allGroups.isEmpty());
            LOG.debug("Board:\n"+board.toString());
            Solution result = new Solution(board, clicks, points);
            LOG.debug("Returning map with these key-value-pairs: ");
            LOG.debug("BOARD:\n"+result.board.toString());
            LOG.debug("KLICKS: "+result.clicks);
            LOG.debug("POINTS: "+result.points);
            return result;
        }
        Solution[] paths = new Solution[allGroups.size()];
        int counter=0;
        for(HashSet<Integer> group : allGroups){
            Board newBoard = new Board(board);
            newBoard.removeGroup(group);
            int newPoints = points + Board.calculatePoints(group.size());
            //TODO das frisst Zeit, man sollte drueber nachdenken, die Groups
            //direkt als ArrayList abzubilden
            ArrayList<Integer> groupList = new ArrayList<Integer>(group);
            if(groupList.size()>0){
                clicks.add(groupList.get(0));
            }else{
                LOG.warn("[getMaxPoints] group-iterator does not find an element");
                clicks.add(Constants.EMPTY);
            }
            paths[counter] = getMaxPoints(newBoard, new ArrayList<Integer>(clicks), newPoints);
            clicks.remove(clicks.size()-1);
            counter++;
        }
        Solution result = new Solution(board, null, -1);
        for(int i=1;i<paths.length;i++){
            if (paths[i].points>result.points){
                result = paths[i];
            }
        }
        return result;
    }


}
